package com.swapper.hls;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TsFileMerger {
  private final String path;
  private final String name;
  private final int count;

  public TsFileMerger(String path, String name, int count) {
    this.path = path;
    this.name = name;
    this.count = count;
  }

  public static void main(String[] args) {
    new TsFileMerger("E:\\Hentai\\uc\\VideoData\\0deef87b242c12f17d64f711c9d3da0d4e7bbe1c", "Y2hlbmppbmdjb25n", 26).merge();
    new TsFileMerger("E:\\Hentai\\uc\\VideoData\\6bd9f0c3e90b47eb50cc0a6e1a6fe33ae12a65aa", "Y2hlbmppbmdjb25n", 19).merge();
    new TsFileMerger("E:\\Hentai\\uc\\VideoData\\44d799b221e72f0c6588960c67613921448365fd", "Y2hlbmppbmdjb25n", 39).merge();
  }

  public void merge() {
    try {
      File mp4File = new File(path + "\\" + name + ".mp4");
      if (mp4File.exists() && !mp4File.delete()) {
        System.out.println("Delete file failure: " + mp4File.getAbsolutePath());
        return;
      }
      if (!mp4File.createNewFile()) {
        System.out.println("Create file failure: " + mp4File.getAbsolutePath());
        return;
      }
      FileOutputStream fileOutputStream = new FileOutputStream(mp4File);
      File tsFile;
      FileInputStream fileInputStream;
      int length;
      byte[] buffer = new byte[4096];
      for (int i = 0; i <= count; ++i) {
        tsFile = new File(path + "\\" + name + i);
        if (!tsFile.exists()) {
          System.out.println("Ts file not exists: " + tsFile.getAbsolutePath());
          continue;
        }
        fileInputStream = new FileInputStream(tsFile);
        while ((length = fileInputStream.read(buffer)) != -1) {
          fileOutputStream.write(buffer, 0, length);
        }
        fileInputStream.close();
        fileOutputStream.flush();
      }
      fileOutputStream.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
